package com.context;

import com.beans.factory.ConfigurableListableBeanFactory;
import com.core.io.Resource;
import com.core.io.ResourcePatternResolver;

import java.io.IOException;

public abstract class AbstractApplicationContext implements ConfigurableApplicationContext{

    private ResourcePatternResolver resourcePatternResolver;

    @Override
    public void refresh()  {

        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        finishBeanFactoryInitialization(beanFactory);
    }

    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){

    }

    protected ConfigurableListableBeanFactory obtainFreshBeanFactory(){

        refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        return beanFactory;
    }

    protected abstract void refreshBeanFactory();

    @Override
    public Resource[] getResources(String locationPattern) throws IOException {
        return this.resourcePatternResolver.getResources(locationPattern);
    }

    //---------------------------------------------------------------------
    // Implementation of BeanFactory interface
    //---------------------------------------------------------------------

    @Override
    public Object getBean(String name) throws Exception {
        assertBeanFactoryActive();
        return getBeanFactory().getBean(name);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws Exception {
        assertBeanFactoryActive();
        return getBeanFactory().getBean(name, requiredType);
    }

    @Override
    public <T> T getBean(Class<T> requiredType) throws Exception {
        assertBeanFactoryActive();
        return getBeanFactory().getBean(requiredType);
    }

    protected void assertBeanFactoryActive() {
//        if (!this.active.get()) {
//            if (this.closed.get()) {
//                throw new IllegalStateException(getDisplayName() + " has been closed already");
//            }
//            else {
//                throw new IllegalStateException(getDisplayName() + " has not been refreshed yet");
//            }
//        }
        return;
    }

    @Override
    public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

}
